{% extends 'wanplus/wangwangba/base_nav_frame.html' %}
{% load staticfiles %}
{% block content %}
  <p>添加内容</p>
  <div>
    <form class="form-horizontal" method="post">
      {% csrf_token %}
      <div class="form-group">
        <label class="col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label" for="title">标题</label>
        <div class="col-lg-3 col-md-3 col-sm-3 col-lg-3">
          <input type="text" class="form-control" id="title" value="{{ content.title }}" />
        </div>
      </div>
      <div class="form-group">
        <label class="col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label" for="type">类型</label>
        <div class="col-lg-3 col-md-3 col-sm-3 col-lg-3">
          <select class="form-control" id="type">
            <option value="1" selected>视频</option>
            <option value="2">分页内容</option>
            <option value="3">订购优惠</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label" for="cover">封面</label>
        <div id="cover-wrapper" class="col-lg-3 col-md-3 col-sm-3 col-lg-3">
          <input type="file" class="form-control" id="cover" name="cover"/>
        </div>
        <div class="col-xs-1 col-md-1 col-lg-1 col-sm-1" id="hint-icon-cover" style="display: none; padding-top: 6px">
          <span class="fa fa-spinner fa-spin"></span>
        </div>
      </div>
      <div id="video-group">
        <div class="form-group">
          <label class="col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label" for="video">视频</label>
          <div id="video-wrapper" class="col-lg-3 col-md-3 col-sm-3 col-lg-3">
            <input type="file" class="form-control" id="video" />
          </div>
          <div class="col-xs-1 col-md-1 col-lg-1 col-sm-1" id="hint-icon-video" style="display: none; padding-top: 6px">
            <span class="fa fa-spinner fa-spin"></span>
          </div>
        </div>
      </div>
      <div id="page-content-group" style="display: none">
        <div class="form-group" id="page-image-group">
          <label class="col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label" for="page-image">图片</label>
          <div id="image-wrapper" class="col-lg-3 col-md-3 col-sm-3 col-lg-3">
            <input type="file" class="form-control" id="page-image" />
          </div>
          <div class="col-xs-1 col-md-1 col-lg-1 col-sm-1" id="hint-icon-image" style="display: none; padding-top: 6px">
            <span class="fa fa-spinner fa-spin"></span>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-md-offset-1 col-sm-offset-1 col-lg-offset-1 col-xs-offset-1 col-xs-3 col-lg-3 col-md-3 col-sm-3">
          <input type="submit" class="btn btn-primary btn-block" id="wb-submit-content-button" value="保  存" />
        </div>
      </div>
    </form>
  </div>
{% endblock %}
{% block jsimport %}
  <script type="text/javascript" src="{% static 'utils/dmuploader.js' %}"></script>
{% endblock %}
{% block jsscript %}
  <script type="text/javascript">
    (function($) {

      $.fn.pageItem = function(option) {

        var defaultOption = {
          titleLabel : ""
          , contentLabel : ""
          , number : 0
          , canRemove : false
          , title : ""
          , content : ""
        };

        var _self = $(this);
        var _option = $.extend({}, defaultOption, option);
        var _onFocusCallback = null;
        var _titleInput = null;
        var _contentInput = null;

        var init = function(option) {

          var titleFormGroup = $("<div />")
              .addClass("form-group");
          var titleLabel = $("<label />")
              .addClass("col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label")
              .text(option.titleLabel);
          var titleInputWrapper = $("<div />")
              .addClass("col-lg-3 col-md-3 col-sm-3 col-lg-3");
          var titleInput = $("<input />")
              .addClass("form-control")
              .attr({
                "type" : "text"
              });
          if (option.title) {
            titleInput.val(option.title);
          }
          titleInputWrapper.append(titleInput);
          titleFormGroup.append(titleLabel);
          titleFormGroup.append(titleInputWrapper);
          _titleInput = titleInput;

          titleInput.focus(function(e) {
            if (_onFocusCallback) {
              _onFocusCallback.apply(_self, [e]);
            }
          });

          var cr = option.canRemove;

          var contentFormGroup = $("<div />")
              .addClass("form-group");
          var contentLabel = $("<label />")
              .addClass("col-xs-1 col-md-1 col-lg-1 col-sm-1 control-label")
              .text(option.contentLabel);
          var contentInputWrapper = $("<div />")
              .addClass("col-lg-3 col-md-3 col-sm-3 col-lg-3");
          var contentInput = $("<textarea />")
              .addClass("form-control");
          if (option.content) {
            contentInput.text(option.content);
          }
          contentInputWrapper.append(contentInput);
          contentFormGroup.append(contentLabel);
          contentFormGroup.append(contentInputWrapper);
          _contentInput = contentInput;

          contentInput.focus(function(e) {
            if (_onFocusCallback) {
              _onFocusCallback.apply(_self, [e]);
            }
          });

          _self.append(titleFormGroup);
          _self.append(contentFormGroup);
        };

        init(_option);

        var o = {
          focus : function() {
            if (arguments.length) {
              if ($.isFunction(arguments[0])) {
                _onFocusCallback = arguments[0];
              }
            } else {
              _titleInput.focus();
              return this;
            }
          }
          , formatValue : function() {
            return JSON.stringify({
              title : _titleInput.val()
              , content : _contentInput.val().replace(/\n/g, "<br />")
            })
          }
        };

        return o;
      };

      $(document).ready(function(e) {
        var pageContentGroup = $("#page-content-group");
        var videoGroup = $("#video-group");
        var pageImageGroup = $("#page-image-group");

        var pageItems = [];

        var coverUrl = "{{ content.coverurl }}";
        var videoToken = "{{ content.video }}";
        var imageToken = "{{ content.image }}";

        var switchGroup = function(type) {
          switch (type) {
            case 1:
              pageContentGroup.hide();
              videoGroup.show();
              break;
            case 2:
              videoGroup.hide();
              pageContentGroup.show();
              break;
            case 3:
              pageContentGroup.hide();
              videoGroup.hide();
              break;
          }
        };

        $("#type").change(function(e) {
          switchGroup(parseInt($(this).val()));
        });
        $("#type").val("{{ content.type }}");
        switchGroup({{ content.type }});

        var insertPageItem = function(pageNumber, defItem, title, content) {
          var pageItemWrapper = $("<div />").addClass("page-item")
              .attr({
                id : "page-item-" + pageNumber
              });
          var option = {
            number : pageNumber
            , canRemove : true
            , titleLabel : "第" + pageNumber + "页标题"
            , contentLabel : "第" + pageNumber + "页内容"
          };
          if (title) {
            option["title"] = title;
          }
          if (content) {
            option["content"] = content ? content.replace(/&lt;br \/&gt;/g, '\n') : "";
          }
          var pageItem = $(pageItemWrapper).pageItem(option);
          pageItemWrapper.insertBefore(defItem);
          pageItem.focus();

          pageItems.push(pageItem);
        };

        var defPageItemWrapper = $("<div />").addClass("page-item");
        var defPageItem = $(defPageItemWrapper).pageItem({
          titleLabel : "添加新页"
        });
        defPageItem.focus(function(e) {
          insertPageItem(pageItems.length + 1, defPageItemWrapper);
        });
        pageContentGroup.append(defPageItemWrapper);

        {% for page in content.pages %}
        insertPageItem({{ forloop.counter }}, defPageItemWrapper, "{{ page.title }}", "{{ page.content }}");
        {% endfor %}

        $("#cover-wrapper").dmUploader({
          url : "./cover/save"
          , dataType : "json"
          , allowedType : "image/*"
          , onInit : function() {
          }
          , onBeforeUpload : function(id) {
            $("#hint-icon-cover").show();
            var iconSpan = $("#hint-icon-cover").find("span");
            if (iconSpan.hasClass("fa-check")) {
              iconSpan.removeClass("fa-check");
            } else if (iconSpan.hasClass("fa-remove")) {
              iconSpan.removeClass("fa-remove");
            }
            iconSpan.addClass("fa-spinner fa-spin");
          }
          , onComplete : function() {
            $("#hint-icon-cover").find("span").removeClass("fa-spinner fa-spin");
          }
          , onUploadSuccess : function(id, data) {
            if (data.resultCode === 1) {
              coverUrl = data.data.filename;
              $("#hint-icon-cover").find("span").addClass("fa-check");
            } else {
              $("#hint-icon-cover").find("span").addClass("fa-exclamation-circle");
            }
          }
          , onUploadError : function(id, message) {
            $("#hint-icon-cover").find("span").addClass("fa-exclamation-circle");
          }
          , onFileTypeError : function(file) {
            $("#hint-icon-cover").find("span").addClass("fa-exclamation-circle");
          }
        });

        $("#video-wrapper").dmUploader({
          url : "./video/save"
          , dataType : "json"
          , allowedType : "image/*"
          , onInit : function() {
          }
          , onBeforeUpload : function(id) {
            $("#hint-icon-video").show();
            var iconSpan = $("#hint-icon-video").find("span");
            if (iconSpan.hasClass("fa-check")) {
              iconSpan.removeClass("fa-check");
            } else if (iconSpan.hasClass("fa-remove")) {
              iconSpan.removeClass("fa-remove");
            }
            iconSpan.addClass("fa-spinner fa-spin");
          }
          , onComplete : function() {
            $("#hint-icon-video").find("span").removeClass("fa-spinner fa-spin");
          }
          , onUploadSuccess : function(id, data) {
            if (data.resultCode === 1) {
              videoToken = data.data.token;
              $("#hint-icon-video").find("span").addClass("fa-check");
            } else {
              $("#hint-icon-video").find("span").addClass("fa-exclamation-circle");
            }
          }
          , onUploadError : function(id, message) {
            $("#hint-icon-video").find("span").addClass("fa-exclamation-circle");
          }
          , onFileTypeError : function(file) {
            $("#hint-icon-video").find("span").addClass("fa-exclamation-circle");
          }
        });

        $("#image-wrapper").dmUploader({
          url : "./image/save"
          , dataType : "json"
          , allowedType : "image/*"
          , onInit : function() {
          }
          , onBeforeUpload : function(id) {
            $("#hint-icon-image").show();
            var iconSpan = $("#hint-icon-image").find("span");
            if (iconSpan.hasClass("fa-check")) {
              iconSpan.removeClass("fa-check");
            } else if (iconSpan.hasClass("fa-remove")) {
              iconSpan.removeClass("fa-remove");
            }
            iconSpan.addClass("fa-spinner fa-spin");
          }
          , onComplete : function() {
            $("#hint-icon-image").find("span").removeClass("fa-spinner fa-spin");
          }
          , onUploadSuccess : function(id, data) {
            if (data.resultCode === 1) {
              imageToken = data.data.token;
              $("#hint-icon-image").find("span").addClass("fa-check");
            } else {
              $("#hint-icon-image").find("span").addClass("fa-exclamation-circle");
            }
          }
          , onUploadError : function(id, message) {
            $("#hint-icon-image").find("span").addClass("fa-exclamation-circle");
          }
          , onFileTypeError : function(file) {
            $("#hint-icon-image").find("span").addClass("fa-exclamation-circle");
          }
        });


        var submitVideoContent = function(token, onDone) {
          var data = {
              title : $("#title").val()
              , type : 1
              , coverurl : coverUrl
              , video : videoToken
            };
          if (token) {
            data.token = token
          }
          $.ajax({
            url : "./save"
            , type : "post"
            , data : data
            , dataType : "json"
            , success : function (data) {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [data && data.resultCode == 1])
              }
            }
            , error : function () {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [false])
              }
            }
          });
        };

        var submitPageContent = function(token, onDone) {
          var pageList = [];
          var length = pageItems.length;
          for (var i = 0; i < length; i++) {
            pageList.push(pageItems[i].formatValue());
          }
          var data = {
              title : $("#title").val()
              , type : 2
              , coverurl : coverUrl
              , image : imageToken
              , pages : pageList
              , datafile : "{{ content.pagedatafile }}"
            };
          if (token) {
            data.token = token;
          }
          $.ajax({
            url : "./save"
            , type : "post"
            , data : data
            , dataType : "json"
            , success : function (data) {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [data && data.resultCode == 1])
              }
            }
            , error : function () {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [false])
              }
            }
          });
        };

        var submitSaleContent = function(token, onDone) {
          var pageList = [];
          var length = pageItems.length;
          for (var i = 0; i < length; i++) {
            pageList.push(pageItems[i].formatValue());
          }
          var data = {
              title : $("#title").val()
              , type : 3
              , coverurl : coverUrl
              , image : imageToken
            };
          if (token) {
            data.token = token;
          }
          $.ajax({
            url : "./save"
            , type : "post"
            , data : data
            , dataType : "json"
            , success : function (data) {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [data && data.resultCode == 1])
              }
            }
            , error : function () {
              if ($.isFunction(onDone)) {
                onDone.apply(this, [false])
              }
            }
          });
        };

        $("#wb-submit-content-button").click(function(e) {
          e.preventDefault();

          var self = $(this);

          self.empty();
          var spinner = $('<span />').addClass("fa fa-spinner fa-spin");
          self.append(spinner);

          var type = parseInt($("#type").val());
          switch (type) {
            case 1:  //视频
                submitVideoContent("{{ content.token }}", function(isOk) {
                  if (!isOk) {
                    alert("保存视频失败");
                  } else {
                    window.location.href = "/wms/plus/wangwangba/content"
                  }
                  self.empty();
                  self.text("保  存");
                });
              break;
            case 2:  //分页
                submitPageContent("{{ content.token }}", function(isOk) {
                  if (!isOk) {
                    alert("保存分页内容失败");
                  } else {
                    window.location.href = "/wms/plus/wangwangba/content"
                  }
                  self.empty();
                  self.text("保  存");
                });
              break;
            case 3:  //订购优惠
                submitSaleContent("{{ content.token }}", function(isOk) {
                  if (!isOk) {
                    alert("保存订购优惠包失败");
                  } else {
                    window.location.href = "/wms/plus/wangwangba/content"
                  }
                  self.empty();
                  self.text("保  存");
                });
              break;
          }
        });

      });
    })(jQuery);
  </script>
{% endblock %}